<?php
namespace control;
/*
*客户类
*/

class clientProfileClass extends adIndexClass
{
    private const title = '客户档案';
    private const page = 'clientProfile';
    private const table = 'kehu';
    /**
     * 客户选择器
     * @param $data
     * @return string
     */
    public static function kehuSelect($data){
        $data['name'] = $data['name']??'khid';
        $data['cla'] = $data['cla']??'clientProfile';
        $data['fun'] = $data['fun']??'getClientList';
        if (isset($data['value']) && !empty($data['value'])){
            $kehu = query('kehu',"khid = '$data[value]'");
            $data['title'] = !empty($data['title']??'')?$data['title']:($kehu['companyName']?:$kehu['contactName']);
        }
        return componentClass::selectText($data);
    }

    /**
     * 有编码和名字
     * @return false|string
     */
    public function getClientNameAndCode(){
        return $this->clientData('code');
    }
    /**
     * 只有名字
     * @return false|string
     */
    public function getClientList(){
        return $this->clientData();
    }
    private function clientData($type=''){
        $val = $this->post('keyword');//关键词
        $json['data'] = [];
        $where = "";
        if ($val){
            $where.=" and (companyName like '%$val%' or orderNo like '%$val%' or concat(orderNo,' ',companyName) like '%$val%')";
        }
        $all = find(array('table' => 'kehu', 'where' => "coid = '" . self::$coid . "'  $where order by orderNo limit 50"));
        foreach ($all['array'] as $array) {
            if ($type=='code'){
                $json['data'][] = array('title' => $array['companyName']?$array['orderNo'].' '.$array['companyName']:$array['orderNo'].'-'.$array['contactName'],'orderNo' => $array['orderNo'], 'id' => $array['khid']);
            }else{
                $json['data'][] = array('title' => $array['companyName']?:$array['contactName'],'orderNo' => $array['orderNo'], 'id' => $array['khid']);
            }
        }
        $json['warn'] = 2;
        return json_encode($json, 320);
    }

    /**
     * 获取客户名称
     * @param $id
     * @param bool $short
     * @param string $interval
     * @return mixed|string
     */
    public static function getName($id,$short = true,$interval = '-'){
        $kehu = query(self::table,"khid = '$id'");
        if (empty($kehu['khid'])){
            return '';
        }
        return $short?$kehu['companyName']:$kehu['orderNo'].$interval.$kehu['companyName'];
    }

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => "客户编码",
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'companyName' => [
                        'name'  => "客户名称",
                        'width' => 150,
                    ],
                    'classify'  => [
                        'name'  => "客户类别",
                        'width' => 150,
                    ],
                    'level'  => [
                        'name'  => '客户等级',
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'contactName'  => [
                        'name'  => '常用联系人',
                        'width' => 150,
                    ],
                    'contactTel'         => [
                        'name'  => '常用联系手机',
                        'width' => 150,
                    ],
                    'contactWx'          => [
                        'name'  => '微信',
                        'width' => 150,
                    ],
                    'contactQQ'          => [
                        'name'  => 'QQ',
                        'width' => 80,
                    ],
                    'companyNum'          => [
                        'name'  => '纳税人识别号',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'manager'          => [
                        'name'  => '销售员',
                        'width' => 150,
                    ],
                    'text'          => [
                        'name'  => '备注',
                        'width' => 150,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "销售员" => selectMultiple(array('table' => 'staff', 'sqlField' => 'name', 'sqlId' => 'stid', 'name' => 'manager', 'class' => 'width200')),
                    "客户名称"   => text(array("name" => "companyName")),
                    "客户编码"   => text(array("name" => "orderNo")),
                ],
                [
                    '联系人'  => text(array("name" => "contactName")),
                    '联系电话'  => text(array("name" => "contactTel")),
                    '纳税人识别码'  => text(array("name" => "companyNum")),
                ],
                [
                    "客户类别" => select(array("name" => "classify", "option" => explode("，", para("clientType")))),
                    "客户等级" => select(array("name" => "level", "option" => explode("，", para("clientLevel")))),
                    "创建时间" => text(array("name" => "time", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*客户列表-查询条件*/
    public function home(): string
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page ;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('新建" . self::title . "','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        //导入
        if ($this->power(self::page, 'import')) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','importFrame',{cla:'".self::page."'})\">导入</span>";
        }
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('".self::page."', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch(): bool|string
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),
            "companyName" => $this->post('companyName'),
            "contactName" => $this->post('contactName'),
            "contactTel" => $this->post('contactTel'),
            "companyNum" => $this->post('companyNum'),
        );
        //全等查询数组
        $equal = array(
            "level" => $this->post('level'),
            "classify" => $this->post('classify'),
            "manager" => $this->post('manager'),

        );
        //公私客
        $and = " and coid = '".self::$coid."'";
        if ($this->post('time')) {
            $timeArr = explode(' ~ ', $this->post('time'));
            $and .= " and date(time) >='{$timeArr[0]}' and date(time) <='{$timeArr[1]}'";
        }
        if (!$this->power(self::page, "seeAll")) {
            //查看自己
            $and .= " and (collaborator like '%" . self::$stid . "%'  or manager = '" . self::$stid . "')";
        }

        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch(self::page.'-homeSearch');
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page ;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['khid']),
                "detail" => array("title" => "客户详情", "click" => "newIframe('客户详情','" . $url . "&fun=detail&id=" . $array['khid'] . "')"),
                "edit" => array("title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['khid'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'manager':
                        $row[] = self::findStaff($array['manager']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id')?:suiji();
        $info = query(self::table, " khid = '" . $id . "' ");
	    $button[]  = [
		    "name"  => '保存',
		    "type"  => "点击事件",
		    "cla"   => $this->get('cla'),
		    "fun"   => "subFormVerify('" . self::page . "EditForm', root+'control/adIndex.html?cla=" . self::page . "&fun=editEdit', root+'control/adIndex.html?cla=" . self::page . "&fun=companyRepeatItemCtrl')",
		    "post"  => ["id" => $this->get('id')],
		    'style' => 'li-btn-blue-bg',
	    ];
        //表单
        $data['button'] = $this->tableShowButton($button);
        $data['html'] = $this->pageEdit([
            "table" => [
                '基本信息' => [
                    [
                        must . "客户名称：" => text(["name" => "companyName", 'class' => 'text', "value" => $info['companyName']]),
                        "性质：" => select(["name" => "nature", 'class' => 'text', 'title' => '请选择', 'option' => explode('，', para('clientNature')), "value" => $info['nature']]),
                        "常用联系人姓名：" => text(["name" => "contactName", 'class' => 'text', "value" => $info['contactName']]),
                        "常用联系人手机：" => text(["name" => "contactTel", 'class' => 'text', "value" => $info['contactTel']]),
                    ],
                    [
                        "常用联系人微信：" => text(["name" => "contactWx", 'class' => 'text', "value" => $info['contactWx']]),
                        "常用联系人QQ：" => text(["name" => "contactQQ", 'class' => 'text', "value" => $info['contactQQ']]),
                        "收货地址：" =>text(["name" => "address", 'title' => '请输入关键词', 'class' => 'text', "value" => $info['address']]) . (componentClass::addressIco("layer('" . self::page . "','map',{})")) .
                            hidden(array('name' => 'location', 'value' => $info['lng'] ? ($info['lat'] . ',' . $info['lng']) : '')),
                    ],
                    [
                        "备注："=>textarea(['name'=>'text','class'=>'textarea','value'=>$info['text']])
                    ],
                ],
                '管理信息' => [
                    [
                        "客户级别：" => select(["name" => "level", 'class' => 'text', 'title' => '请选择', 'option' => explode('，', para('clientLevel')), "value" => $info['level']]),
                        "客户类别：" => select(["name" => "classify", 'class' => 'text', 'title' => '请选择', 'option' => explode('，', para('clientType')), "value" => $info['classify']]),
                        "来源：" => select(["name" => "source", 'class' => 'text', 'title' => '请选择', 'option' => explode('，', para('clientSource')), "value" => $info['source']]),
                        must . "负责人：" => selectMultiple(array('table' => 'staff', "title" => '请选择', 'sqlField' => 'name', 'sqlId' => 'stid', 'name' => 'manager', 'value' => $info['manager'] ?: self::$stid)),
                    ],
                    [
                        "协作人：" => selectMultiple(array('table' => 'staff', 'where' => " stid !='$info[manager]'", 'multiple' => true, "title" => '请选择', 'sqlField' => 'name', 'sqlId' => 'stid', 'name' => 'collaborator[]', 'value' => $info['collaborator'])),
                    ],
                ],
                '开票信息' => [
                    [
                        "发票类型：" => radio(array("name" => "invoiceType",'value'=>['普票','专票'], "checked" => $info['invoiceType']?:'普票')),
                        "默认税率(%)：" => select(array("name" => "taxRate",'option'=>explode('，',para('taxRate')),'title'=>'请选择', "value" => (float)$info['taxRate']*100)),
                        "开户行：" => text(array("name" => "companyBank", "value" => $info['companyBank'])),
                        "银行账号：" => text(array("name" => "companyBankNum", "value" => $info['companyBankNum'])),
                    ],
                    array(
                        "注册地址、电话：" => text(array("name" => "companyAddress", "value" => $info['companyAddress'])),
                        "纳税人识别号：" => text(array("name" => "companyNum", "value" => $info['companyNum'])),
                        "默认付款方式：" => select(array("name" => "payType",'option'=>explode('，',para('payType')),'title'=>'请选择', "value" => $info['payType'])),
                        "信用额度：" => text(array("name" => "credits",'unit'=>static::$unit, "value" => $info['credits'])),
                    ),
                    array(
                        "默认结算方式：" => radio(array("name" => "settleType",'value'=>explode('，',para('supplierSettlement')), "checked" => $info['settleType'])),
                        "对账日：" => text(array("name" => "checkDay","value" => $info['checkDay'])),
                    )
                ],
            ],
            'hidden' => hidden(['name' => 'id', 'value' => $id]),
        ]);
        $data['html'] .= <<<efo
<script>

$(function(){
    $("input[name='address']").bigAutocomplete({
        // width:543,
        url:root + 'control/adIndex.html?cla=component&fun=getAddress',
        callback:function(data){
            $("[name='location']").val(data.location);
            $("[name='region']").val(data.province+'-'+data.city)
        }
    });
})
</script>
efo;


        //返回
        return $this->tab($data);
    }
    /**
     * 地图选址
     */
    public function map(): bool|string
    {
        $key = para('tencentMapKey');
        $html = <<<efo
<iframe id="mapPage" width="100%" height="90%" frameborder=0
    src="https://apis.map.qq.com/tools/locpicker?search=1&type=1&key={$key}&referer=myapp">
</iframe>
<div style="text-align: center;padding: 10px"><input onclick="$('#clientProfileMap').hide()" class="button" type="button" value="确认"></div>
<script>
    window.addEventListener('message', function(event) {
        // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
        var loc = event.data;
        if (loc && loc.module == 'locationPicker') {//防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
            //移除监听
           event.stopPropagation();
          $("[name='location']").val(loc.latlng.lat+','+loc.latlng.lng);
          $("[name='address']").val(loc.poiaddress);
        }
    }, false);
</script>
efo;

        return $this->layer(array("title" => "地图选址", "height" => 800, "width" => 1000, "html" => $html, "button" => false));
    }

    /*异步处理*/
    public function companyRepeatItemCtrl(): bool|string
    {
        $id     = $this->post('id') ?: self::getId();
        $field = [
            "companyName" => $this->post('companyName'),//公司名称
            "contactName" => $this->post('contactName'),//联系人姓名
        ];
        $json = [];
        //重复检查
        $setItem = ['companyName' => ['companyName'=>'公司名称'], 'contactName' => ['contactName'=>'常用联系人']];
        $optionSetting = optionSettingClass::getSetting('公共');  //选项设置
        $companyRepeatItemCtrl = $optionSetting['companyRepeatItemCtrl'];  //重复检查项
        $checkItem = [];
        foreach ($companyRepeatItemCtrl as $val){
            $checkItem = array_merge($checkItem,(isset($setItem[$val])?$setItem[$val]:[]));
        }
        $repeat = array(
            "khid" => $id,
            "field" => $field,
            //"name" => array("contactTel" => "联系人手机号码", "contactQQ" => "联系人QQ", "companyName" => "公司名称", "companyNum" => "纳税人识别号"),
            "name" => $checkItem,
        );
        $warn = $this->repeat($repeat);
        if ($warn) {
            switch ($optionSetting['companyRepeatCtrl']) {
                case "禁止":
                    $json['allow'] = 0;
                    $json['warn'] = $warn;
                    break;
                default:
                    $json['allow'] = 1;
                    $json['warn'] = $warn."，是否选择继续提交？";
            }
        }else{
            $json['warn'] = 2;
        }
        //返回
        resp:
        return json_encode($json, 320);
    }

    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $field = [
            "contactName" => $this->post('contactName'),//联系人姓名
            "contactTel" => $this->post('contactTel'),//联系人手机号码
            "contactQQ" => $this->post('contactQQ'),//联系人QQ号码
            "contactWx" => $this->post('contactWx'),//联系人微信号
            "nature" => $this->post('nature'),
            "settleType" => $this->post('settleType'),
            "checkDay" => $this->post('checkDay'),
            "payType" => $this->post('payType'),//跟进状态
            "credits" => $this->post('credits'),//客户来源
            "level" => $this->post('level'),
            "classify" => $this->post('classify'),
            'invoiceType' => $this->post('invoiceType'),
            "taxRate" => (float)$this->post('taxRate')/100,//所在行业
            "text" => $this->post('text'),
            "companyName" => $this->post('companyName'),//公司名称
            "companyNum" => $this->post('companyNum'),//纳税人识别号
            "companyBank" => $this->post('companyBank'),//公司开户银行
            "companyBankNum" => $this->post('companyBankNum'),//对公账号
            "companyAddress" => $this->post('companyAddress'),//开票地址
            'poolId' => $this->post('taxRate') ?: clientClass::defaulPoolId(),
            'manager' => $this->post('manager'),
            'source' => $this->post('source'),
            'collaborator' => $this->post('collaborator') && is_array($this->post('collaborator')) ? implode(',', array_unique($this->post('collaborator'))) : '',
            "address" => $this->post('address'),
        ];
        $annotation = [
            'companyName' => '客户名称',
            'manager' => '负责人',
        ];
        $rules = [
            'companyName' => 'required',
            'manager' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $where = " khid = '$id' ";
        $info = query(self::table, $where);
        //重复检查
        $setItem = ['companyName' => ['companyName'=>'公司名称'], 'contactName' => ['contactName'=>'常用联系人']];
        $optionSetting = optionSettingClass::getSetting('公共');  //选项设置
        $companyRepeatItemCtrl = $optionSetting['companyRepeatItemCtrl'];  //重复检查项
        $checkItem = [];
        foreach ($companyRepeatItemCtrl as $val){
            $checkItem = array_merge($checkItem,($setItem[$val] ?? []));
        }
        $repeat = array(
            "khid" => $id,
            "field" => $field,
            //"name" => array("contactTel" => "联系人手机号码", "contactQQ" => "联系人QQ", "companyName" => "公司名称", "companyNum" => "纳税人识别号"),
            "name" => $checkItem,
        );
        $warn = $this->repeat($repeat);
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        }  elseif (!empty($field['contactQQ']) && preg_match(checkInteger, $field['contactQQ']) == 0) {
            $json['warn'] = 'QQ号码格式错误';
        }elseif (is_array($this->post('collaborator')) && in_array($field['manager'], $this->post('collaborator'))) {
            $json['warn'] = '所选的协作人中包含了负责人';
        } elseif (!$this->power(self::page,'seeAll') && !empty($info['khid']) && !in_array($this->control['stid'], explode(",", $info['see']))) {
            $json['warn'] = "这不是你的客户，你也不是协作人";
        } elseif ($warn && $optionSetting['companyRepeatCtrl'] == '禁止') {
            $json['warn'] = $warn;
        } else {
            //查看范围
            $field['see'] = implode(',', array_filter(array_unique(array_merge(explode(',', $field['collaborator']), [$field['manager']]))));
            if ($this->post('location')){
                $location = explode(',', $this->post('location'));
                $field['lat'] = $location[0];
                $field['lng'] = $location[1];
                $region = componentClass::coordinateToAddr($field['lat'], $field['lng']);
                if ($region['err_code'] == 0) {
                    $field['region'] = $region['data']['address_component']['province'] . '-' . $region['data']['address_component']['city'] . '-' . $region['data']['address_component']['district'];
                }
            }
            if (!$info['khid']) {
                $userNo = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'C',
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => " and coid = '".self::$coid."'",
                ],$field);
                $field = array_merge($field, [
                    'khid' => $id,
                    'isDeal'=>1,
                    'data_source'=>1,
                    'coid'=>self::$coid,
                    'orderNo'=>$userNo,
                    'stid' => $this->control['stid'],
                    'time' => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where,
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                if (!empty($field['contactName']) && !empty($field['contactTel'])){
                    $contact  =query('kehu_staff',"khid = '$id' and tel = '$field[contactTel]'");
                    if (empty($contact['id'])){
                        static::insert(array(
                           'table'=>'kehu_staff',
                           'field'=>[
                               'id'=>suiji(),
                               'khid'=>$id,
                               'coid'=>self::$coid,
                               'stid'=>self::$stid,
                               "name" => $field['contactName'],//姓名
                               "tel" => $field['contactTel'],//手机
                               "qq" => $field['contactQQ'],//QQ号码
                               "WeChat" => $field['contactWx'],//微信号
                               "text" => '常用联系人',//备注
                           ]
                        ));
                    }else{
                        static::update(array(
                            'table'=>'kehu_staff',
                            'field'=>[
                                "name" => $field['contactName'],//姓名
                                "tel" => $field['contactTel'],//手机
                                "qq" => $field['contactQQ'],//QQ号码
                                "WeChat" => $field['contactWx'],//微信号
                                "text" => '常用联系人',//备注
                            ],
                            'where'=>"id = '$contact[id]'"
                        ));
                    }
                }
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'].($warn?'，'.$warn:'');
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }




    /*客户查看权限*/
    public function clientSee($khid)
    {
        //数据库查询
        $kehu = query("kehu", " khid = '$khid' ");
        //验证
        if (empty($khid)) {
            $json['warn'] = "客户ID为空";
        } elseif (empty($kehu['khid'])) {
            $json['warn'] = "未找到此客户";
        } elseif (!$this->power(self::page, "seeAll")) {
            //不是公客，又没有查看所有客户的权限
            if (!$this->power(self::page, "see")) {
                //有查看自己客户的权限
                $json['warn'] = "你没有查看的权限";
            } elseif (!in_array($this->control['stid'], explode(",", $kehu['see']))) {
                $json['warn'] = "这不是您的客户，您也不是协作人";
            } else {
                $json['warn'] = "";
            }
        } else {
            $json['warn'] = "";
        }
        if (empty($json['warn'])) {
            $json = $kehu;
        }
        //返回
        return $json;
    }

    /*客户管理-客户详情页*/
    public function detail()
    {
        $kehu = $this->clientSee($this->get('id'));
        if (!empty($kehu['warn'])) {
            $html = $kehu['warn'];
        } else {
            //菜单
            $data = array(
                "id" => $kehu['khid'],
                "title" => kong($kehu['companyName']),
                "menu" => array(
                    "detail" => "基本信息",
                    "contacts" => "联系人",
                    "file" => array("name" => "客户附件", "cla" => "file", "fun" => "clientFile"),
                    "contract" => array("name" => "合同", "cla" => "salesContract", "fun" => "clientContract"),
                    "saleOrder" => array("name" => "销售订单", "cla" => "saleOrder", "fun" => "clientOrder"),
                    "saleSend" => array("name" => "销售发货", "cla" => "saleSendOrder", "fun" => "clientSendOrder"),
                    "saleRefund" => array("name" => "销售退货", "cla" => "saleRefundOrder", "fun" => "clientRefundOrder"),
                    "income" => array("name" => "收款记录", "cla" => "inReceipt", "fun" => "clientIn"),
                    "invoice" => array("name" => "开票记录", "cla" => "saleInvoice", "fun" => "clientInvoice"),
                    "record" => array("name" => "跟进记录", "cla" => "follow", "fun" => "clientRecord"),
                    "clientPrice" => array("name" => "价格本", "cla" => "clientPriceList", "fun" => "clientPrice"),
                    "aftermarket" => array("name" => "售后记录", "cla" => "aftermarketRecord", "fun" => "aftermarket"),
                )
            );
            //按钮
            $button = [];
            if ($this->power("client", "edit") and self::$stid == $kehu['manager']) {
                //按钮
                $button[] = [
                    "name" => "编辑",
                    "type" => "顶部页卡",
                    "title" => "编辑",
                    "url" => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=edit&id=' . $kehu['khid'],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            if ($this->power(self::page, "del") and self::$stid == $kehu['manager']) {
                //按钮
                $button[] = [
                    "name" => "删除",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $kehu['khid']],
                ];
            }


            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                "基本信息" => array(
                    array(
                        "客户编码" => $kehu['orderNo'],
                        "客户名称" => $kehu['companyName'],
                        "性质" => $kehu['nature'],
                        "常用联系人姓名" => $kehu['contactName'],
                    ),
                    array(
                        "常用联系人手机" => $kehu['contactTel'],
                        "常用联系人微信号" => $kehu['contactWx'],
                        "常用联系人QQ" => $kehu['contactQQ'],
                    ),
                    array(
                        "备注" => pre($kehu['text']),
                    ),
                ),
                "管理信息" => array(
                    array(
                        "负责人" => self::findStaff($kehu['manager']),
                        "客户级别" => $kehu['level'],
                        "客户类别" => $kehu['classify'],
                        "来源" => $kehu['source'],
                    ),
                    array(
                        "协作人" => clueClass::showMember($kehu['collaborator']),

                    ),
                ),
                "财务信息" => array(
                    array(
                        "发票类型" => $kehu['invoiceType'],
                        "默认税率" => ($kehu['taxRate']*100).'%',
                        "开户行" => $kehu['companyBank'],
                        "银行账号" => $kehu['companyBankNum'],
                    ),
                    array(
                        "注册地址，电话" => $kehu['companyAddress'],
                        "纳税人识别号" => $kehu['companyNum'],
                        "默认付款方式" => $kehu['payType'],
                        "信用额度（".static::$unit."）" => $kehu['credits'],
                    ),
                    array(
                        "默认结算方式" => $kehu['settleType'],
                        "对账日" => $kehu['checkDay'],
                    ),
                ),
                "系统信息" => array(
                    array(
                        "创建人" => self::findStaff($kehu['stid']),
                        "创建时间" => $kehu['time'],
                        "更新时间" => $kehu['updateTime'],
                    ),
                ),
            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }


    /*客户管理-客户列表-联系人*/
    public function contacts()
    {
        $edit = $del = '';
        if ($this->power(self::page, "staffEdit")) {
            $edit = "<span class='spanButton' title='新增客户联系人' onclick=\"layer('" . self::page . "','staff',{id:'" . suiji() . "',clientId:'" . $this->get('id') . "'})\">新增</span>\n";
        }
        if ($this->power(self::page, "staffDel")) {
            $del = "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'delContact'})\">删除</span>\n";
        }
        $checkAll = $this->checkAll("clientContactsForm", "clientStaffId");
        $tr[] = array($checkAll, "姓名", '性别', "职务", "手机", "电话", "微信", "QQ", "生日", '地址', "备注", "更新时间");
        $sql = find(array("table" => "kehu_staff", "where" => " khid = '" . $this->get('id') . "' order by updateTime desc "));
        foreach ($sql['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "clientStaffId", "value" => $array['id']),
                "edit" => array("title" => "编辑", "click" => "layer('" . self::page . "','staff',{id:'" . $array['id'] . "'})"),
            );
            $tr[] = array($this->dominate($dominate), $array['name'], $array['sex'], $array['position'], $array['tel'], $array['phone'], $array['WeChat'], $array['qq'], self::null($array['birthDay']), $array['address'], $array['text'], $array['updateTime']);
        }
        $json['html'] =  "<div class='p-10'><div class='flex-box'>". $edit . $del ."</div>".space."<form name='clientContactsForm'>" . $this->tableMany(array("tr" => $tr, "displayFields"=>false)) . "</form></div>";
        return json_encode($json, 320);
    }

    /*客户管理-客户列表-编辑联系人*/
    public function staff()
    {
        $hidden='';
        $kehuStaff = query("kehu_staff", " id = '" . $this->post('id') . "' ");
        if (empty($this->post('id'))) {
            $html = "联系人ID为空";
        } elseif (empty($kehuStaff['id'])) {
            $kehu = query("kehu", " khid = '" . $this->post('clientId') . "' ");
            $hidden = hidden(array("name" => "clientId", "value" => $kehu['khid']));
        }
        if (empty($html)) {
            $html = $this->layerEdit(array("table" => array(
                array(
                    must . "姓名：" => text(array("name" => "name", "class" => "text", "value" => $kehuStaff['name'])),
                    must . "性别：" => radio(array("name" => "sex", 'value' => ['男', '女'], "checked" => $kehuStaff['sex'])),
                ),
                array(
                    "部门：" => text(array("name" => "department", "class" => "text", "value" => $kehuStaff['department'])),
                    "职位：" => text(array("name" => "position", "class" => "text", "value" => $kehuStaff['position'])),
                ),
                array(
                    must . "手机：" => text(array("name" => "tel", "class" => "text", "value" => $kehuStaff['tel'])),
                    "电话：" => text(array("name" => "phone", "class" => "text", "value" => $kehuStaff['phone'])),
                ),
                array(
                    "微信：" => text(array("name" => "WeChat", "class" => "text", "value" => $kehuStaff['WeChat'])),
                    "QQ：" => text(array("name" => "qq", "class" => "text textPrice", "value" => $kehuStaff['qq'])),
                ),
                array(
                    "地址：" => text(array("name" => "address", "class" => "text", "value" => $kehuStaff['address'])),
                    "生日：" => text(array("name" => "birthDay", "class" => "text", 'laydate' => [], "value" => self::null($kehuStaff['birthDay'], false))),
                ),
                array(
                    "备注：" => textarea(array("name" => "text", "class" => "textarea", "value" => $kehuStaff['text'])),
                )
            ), "hidden" => $hidden));
        }
        return $this->layer(array("title" => "编辑客户联系人", "height" => 400, "width" => 800, "html" => $html));
    }

    /*客户管理-客户列表-联系人-编辑*/
    public function staffEdit()
    {
        //赋值
        $field = array(
            "sex" => $this->post('sex'),
            "position" => $this->post('position'),//职位
            "name" => $this->post('name'),//姓名
            "department" => $this->post('department'),
            "birthDay" => $this->post('birthDay'),
            "tel" => $this->post('tel'),//手机
            "phone" => $this->post('phone'),//座机
            "qq" => $this->post('qq'),//QQ号码
            "WeChat" => $this->post('WeChat'),//微信号
            "address" => $this->post('address'),//排序号
            "text" => $this->post('text'),//备注
            "updateTime" => date("Y-m-d H:i:s"),//更新时间
        );
        //数据库查询
        $kehuStaff = query("kehu_staff", " id = '" . $this->post('id') . "' ");
        if (empty($kehuStaff['khid'])) {
            $kehu = query("kehu", " khid = '" . $this->post('clientId') . "' ");
            if (empty($this->post('clientId'))) {
                $json['warn'] = "客户ID号为空";
            } elseif (empty($kehu['khid'])) {
                $json['warn'] = "未找到此客户";
            }
        } else {
            $kehu = query("kehu", " khid = '$kehuStaff[khid]' ");
        }
        //判断
        if (!$this->power("client", "staffEdit")) {
            $json['warn'] = "您没有编辑客户联系人的权限";
        } elseif (empty($field['name'])) {
            $json['warn'] = "请输入姓名";
        } elseif (empty($field['sex'])) {
            $json['warn'] = "请选择性别";
        } elseif (empty($field['tel'])) {
            $json['warn'] = "请输入手机号码";
        } elseif (preg_match(checkTel, $field['tel']) == 0) {
            $json['warn'] = "联系手机格式有误";
        } elseif (sqlNum("kehu_staff", " tel = '$field[tel]' and khid = '$kehu[khid]' and id != '" . $this->post('id') . "' ") > 0) {
            $json['warn'] = "此客户的联系人中已经存在本手机号码了";
        } elseif (!empty($field['qq']) and preg_match(checkInteger, $field['qq']) == 0) {
            $json['warn'] = "QQ号码必须为正整数";
        } elseif (empty($kehuStaff['id'])) {
            $field = array_merge($field, array("id" => $this->post('id'), 'coid'=>self::$coid,"stid" => $this->control['stid'], "khid" => $this->post('clientId'), "time" => date("Y-m-d H:i:s")));
            $json['warn'] = insert(array("table" => "kehu_staff", "field" => $field));
        } else {
            $json['warn'] = update(array("table" => "kehu_staff", "field" => $field, "where" => " id = '$kehuStaff[id]' "));
        }
        if (in_array($json['warn'], array("新增成功", "更新成功"))) {
            //添加日志
            $type = mb_substr($json['warn'], 0, 2, 'utf-8');
            $text = $this->control['name'] . "为客户【" . $kehu['companyName'] . "】【客户ID：" . $kehu['khid'] . "】" . $type . "了一个客户联系人：" . $field['name'] . "ID号：" . $this->post('id');
            $this->logText(array("type" => "client", "text" => $text));
            //返回
            $_SESSION['warn'] = $json['warn'];
            $json['warn'] = 2;
        }
        $json['href'] = root . "control/adIndex.html?cla=client&fun=detail&menu=contacts&id=" . $kehu['khid'];
        return json_encode($json, 320);
    }

    /*客户资料排重*/
    public function repeat($data)
    {
        foreach ($data['name'] as $name => $explain) {
            if (!empty($data['field'][$name])) {
                //客户排重查询
                $kehu = query("kehu", $name . " = '" . $data['field'][$name] . "' and khid != '$data[khid]' and coid = '".self::$coid."' ");
                if (!empty($kehu['khid'])) {
                    return "【" . $kehu['companyName'] . "】存在相同的" . $explain . "【" . $data['field'][$name] . "】";
                }
            }
        }
        return false;
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $word = $power = '';
        switch ($act) {
            case 'delContact':
                $act = 'staffDel';
                $msg = '删除客户联系人';
                $title = 'clientContactsDelete';
                $function = 'contactsDelete';
                $form = self::page . 'OperateForm, clientContactsForm';

                break;
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = 'clientDelete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " khid = '$id' ");
                if ($info['manager'] != self::$stid) {
                    //返回
                    $warn = "删除失败：这不是您的客户";
                }elseif(static::total(array('table'=>'opportunity','where'=>"khid = '$id'")) >0){
                    $warn ="已有商机使用，不能删除";
                }elseif(static::total(array('table'=>'quotations','where'=>"khid = '$id'")) >0){
                    $warn ="已有报价单使用，不能删除";
                }elseif(static::total(array('table'=>'sales_contract','where'=>"clientId = '$id'")) >0){
                    $warn ="已有销售合同使用，不能删除";
                }elseif(static::total(array('table'=>'sale_order','where'=>"khid = '$id'")) >0){
                    $warn ="已有销售单据使用，不能删除";
                } elseif(static::total(array('table'=>'sale_send_order','where'=>"khid = '$id'")) >0){
                    $warn ="已有销售发货单据使用，不能删除";
                }elseif(static::total(array('table'=>'sale_refund_order','where'=>"khid = '$id'")) >0){
                    $warn ="已有销售退货单据使用，不能删除";
                }else {
                    $result = find(array('table' => 'file', 'where' => "targetId = '$id'"));
                    foreach ($result['array'] as $file) {
                        fileDelete($file['src']);
                    }
                    //删除附件
                    delete(array("table" => "file", "where" => " targetId = '$id' "));
                    //删除标签
                    delete(array("table" => "kehu_label", "where" => " targetId = '$id' "));
                    //删除跟进记录
                    delete(array("table" => "follow", "where" => " targetId = '$id' "));
                    //删除操作日志
                    delete(array("table" => "clue_log", "where" => " orderId = '$id' "));
                    //删除客户联系人
                    delete(array("table" => "kehu_staff", "where" => " khid = '$id' "));
                    //删除拜访记录
                    delete(array("table" => "visit_plan", "where" => " khid = '$id' "));
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " khid = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['khid'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /*客户管理-客户列表-联系人-批量删除*/
    public function contactsDelete(): bool|string
    {
        if (!$this->power("client", "staffDel")) {
            $json['warn'] = "你没有删除客户联系人的权限";
        } elseif (empty($this->post('clientStaffId'))) {
            $json['warn'] = "你一个联系人都没有选择呢";
        } else {
            $x = 0;
            foreach ($this->post('clientStaffId') as $id) {
                $kehuStaff = query("kehu_staff", " id = '$id'");
                $kehu = query("kehu", " khid = '$kehuStaff[khid]' ");
                //删除客户联系人基本参数
                delete(array("table" => "kehu_staff", "where" => " id = '$id' "));
                //添加日志
                $text = $this->control['name'] . "删除了一个客户的联系人：<br>
				公司名称：" . kong($kehu['companyName']) . "<br>
				职位：" . $kehuStaff['position'] . "<br>
				姓名：" . $kehuStaff['name'] . "<br>
				手机：" . $kehuStaff['tel'];
                $this->logText(array("type" => "client", "text" => $text));
                $x++;
            }
            $_SESSION['warn'] = "删除了" . $x . "个客户联系人";
            $json['href'] = root . "control/adIndex.html?cla=client&fun=detail&menu=contacts&id=" . $kehu['khid'];
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }

    /**
     * 下载模板
     */
    public function downloadModel()
    {
        $templateId = $this->get('templateId');
        if (!$this->power(self::page, 'import')) {
            $_SESSION['warn'] = '你还没有导入的权限';
        }  else {
            $exampleData[] = ['K0001','重庆雨木科技','民营企业','邱女士', '13000000000','wechat001','10001','重庆市国际社区','A类','软件信息行业','官网','张三','YM202111220001','李四,王五',
                'YM202111220002,YM202111220003','普票',0.1,'中国工商银行','000000000001','重庆市 44310001','0002121111111','现金',10000,'现付','每月1号','(样例数据，导入时请删除本条数据)'];

            $excel    = $this->excelHead();
            $fileName = self::title.'导入模板-'.importTemplateClass::getName($templateId).'.xlsx';
            $filePath = $excel->fileName($fileName, 'sheet1');
            $format = new \Vtiful\Kernel\Format($filePath->getHandle());
            $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
            $index         = 0;
            foreach ($templateField as $k => $array) {
                if ($array['display']){
                    $backgroundStyle=null;
                    if (importTemplateClass::getIsMustValue($this->importFieldInit(), $array['columnName'])){
                        //必填项判断
                        $backgroundStyle  = $format->background(
                            0xFFC04B
                        )->toResource();
                    }
                    $filePath->insertText(0, $index, $array['aliasName'],'',$backgroundStyle);
                    foreach ($exampleData as $y=>$example){
                        $exampleVal = match ($array['columnName']){
                            '客户编号'=>$example[0],
                            '客户名称'=>$example[1],
                            '性质'=>$example[2],
                            '常用联系人姓名'=>$example[3],
                            '常用联系人手机'=>$example[4],
                            '常用联系人微信'=>$example[5],
                            '常用联系人QQ'=>$example[6],
                            '收货地址'=>$example[7],
                            '客户级别'=>$example[8],
                            '客户类别'=>$example[9],
                            '来源'=>$example[10],
                            '负责人'=>$example[11],
                            '负责人编号'=>$example[12],
                            '协作人'=>$example[13],
                            '协作人编号'=>$example[14],
                            '发票类型'=>$example[15],
                            '默认税率'=>$example[16],
                            '开户行'=>$example[17],
                            '银行账号'=>$example[18],
                            '注册地址、电话'=>$example[19],
                            '纳税人识别号'=>$example[20],
                            '默认付款方式'=>$example[21],
                            '信用额度'=>$example[22],
                            '默认结算方式'=>$example[23],
                            '对账日'=>$example[24],
                            '备注'=>$example[25],
                            default=>'',
                        };
                        $filePath->insertText($y+1, $index, $exampleVal);
                    }
                    $index++;
                }
            }

            $text = $this->control['name'] . "下载了客户导入模板";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOutPut($filePath,$fileName);
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }


    /*数据导入*/
    public function importData()
    {
        $templateId = $this->post('templateId');
        if (!$this->power(self::page, 'import')) {
            $json['warn'] = '你还没有导入的权限';
        } else {
             $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
            $x = 0;
            $text = '';
            $settleTypeOption = explode('，',para('supplierSettlement'));
            $invoiceTypeOption = ['普票','专票'];
            $payTypeOption = explode('，',para('payType'));
            $levelOption = explode('，', para('clientLevel'));
            $clientTypeOption = explode('，', para('clientType'));
            $natureOption = explode('，', para('clientNature'));
            $sourceOption = explode('，', para('clientSource'));
            $headArray = [];
            $row_list=0;
            foreach ($data as $i => $row) {
                $row_list++;
                if ($i==0){
                    $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
                    $headArray = importTemplateClass::combinHead($templateField,$row);
                }
                if ($i > 0) {
                    $rowData = formSubArray($row);
                    //只接收模板中选中的字段的值
                    $cell = [];
                    foreach ($headArray as $index=>$headName){
                        $cell[$headName] = $rowData[$index]??'';
                    }
                    //初始化未被模板需要的字段的值
                    foreach ($this->importFieldInit() as $value){
                        $cell[$value['columnName']] = $cell[$value['columnName']]??'';
                    }
                    $manager = query("staff", "orderNo = '$cell[负责人编号]'");
                    $partner = explode(',', $cell['协作人编号']);

                    $collaborator = [];
                    foreach ($partner as $stid) {
                        $staff = query('staff', "orderNo = '$stid' and orderNo !=''");
                        $collaborator[] = $staff['stid'];
                    }

                    $id = self::getId();
                    $field = [
                        "companyName" => $cell['客户名称'],//公司名称
                        "nature" => $cell['性质'],
                        "contactName" => $cell['常用联系人姓名'],//联系人姓名
                        "contactTel" => $cell['常用联系人手机'],//联系人手机号码
                        "contactQQ" => $cell['常用联系人QQ'],//联系人QQ号码
                        "contactWx" => $cell['常用联系人微信'],//联系人微信号
                        "address" => $cell['收货地址'],
                        "level" => $cell['客户级别'],
                        "classify" => $cell['客户类别'],
                        "source" => $cell['来源'],
                        "invoiceType" => $cell['发票类型'],
                        "taxRate" => (float)$cell['默认税率']/100,
                        "companyBank" => $cell['开户行'],
                        "companyBankNum" => $cell['银行账号'],//对公账号
                        "companyAddress" => $cell['注册地址、电话'],//开票地址
                        "companyNum" => $cell['纳税人识别号'],//纳税人识别号
                        "payType" => $cell['默认付款方式'],
                        "credits" => $cell['信用额度'],
                        "settleType" => $cell['默认结算方式'],
                        "checkDay" => $cell['对账日'],
                        "text" => $cell['备注'],
                        'poolId' => clientClass::defaulPoolId(),
                        'manager' => $cell['负责人编号']?$manager['stid']:self::$stid,
                        'collaborator' => implode(',', array_filter(array_unique($collaborator))),
                        'region'=>'',
                        'lat'=>'',
                        'lng'=>'',
                    ];

                    $annotation = [
                        'companyName' => '客户名称',
                        'manager' => '负责人',
                    ];
                    $rules = [
                        'companyName' => 'required',
                        'manager' => 'required',
                    ];
                    //重复检查
                    $setItem = ['companyName' => ['companyName'=>'公司名称'], 'contactName' => ['contactName'=>'常用联系人']];
                    $optionSetting = optionSettingClass::getSetting('公共');  //选项设置
                    $companyRepeatItemCtrl = $optionSetting['companyRepeatItemCtrl'];  //重复检查项
                    $checkItem = [];
                    foreach ($companyRepeatItemCtrl as $val){
                        $checkItem = array_merge($checkItem,($setItem[$val] ?? []));
                    }
                    $repeat = array(
                        "khid" => $id,
                        "field" => $field,
                        //"name" => array("contactTel" => "联系人手机号码", "contactQQ" => "联系人QQ", "companyName" => "公司名称", "companyNum" => "纳税人识别号"),
                        "name" => $checkItem,
                    );
                    $warn = $this->repeat($repeat);
                    // 校验是否符合规则
                    $vt = new \verify();
                    $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
                    if (!empty($cell['负责人编号']) && !$manager['stid']) {
                        $text .= "第【{$row_list}】行：未通过员工编号找到此员工";
                    } elseif ($result === false) {
                        $text .= "\n第【{$row_list}】行：" . $vt->getErrs()[0];
                    } elseif(!empty($field['orderNo']) && static::total(['table'=>'kehu','where'=>"orderNo = '$field[orderNo]' and coid = '".self::$coid."' and khid !='$field[khid]'"]) >0){
                        $text .= "\n第【{$row_list}】行：" . '已存在此编码的客户';
                    } elseif (!empty($field['contactQQ']) && preg_match(checkInteger, $field['contactQQ']) == 0) {
                        $text .= "\n第【{$row_list}】行：" . 'QQ号码格式错误';
                    }  elseif (is_array($this->post('collaborator')) && in_array($field['manager'], $this->post('collaborator'))) {
                        $text .= "\n第【{$row_list}】行：" . '所选的协作人中包含了负责人';
                    } elseif ($warn && $optionSetting['companyRepeatCtrl'] == '禁止') {
                        $text .= "\n第【{$row_list}】行：" . $warn;
                    }elseif(!empty($field['nature']) && !in_array($field['nature'],$natureOption)){
                        $text .= "\n第【{$row_list}】行：性质不在可选范围内";
                    } elseif(!empty($field['level']) && !in_array($field['level'],$levelOption)){
                        $text .= "\n第【{$row_list}】行：客户级别不在可选范围内";
                    } elseif(!empty($field['payType']) && !in_array($field['payType'],$payTypeOption)){
                        $text .= "\n第【{$row_list}】行：默认付款方式不在可选范围内";
                    } elseif(!empty($field['classify']) && !in_array($field['classify'],$clientTypeOption)){
                        $text .= "\n第【{$row_list}】行：客户类别不在可选范围内";
                    }  elseif(!empty($field['source']) && !in_array($field['source'],$sourceOption)){
                        $text .= "\n第【{$row_list}】行：客户来源不在可选范围内";
                    }  elseif(!empty($field['invoiceType']) && !in_array($field['invoiceType'],$invoiceTypeOption)){
                        $text .= "\n第【{$row_list}】行：发票类型不在可选范围内";
                    } elseif(!empty($field['settleType']) && !in_array($field['settleType'],$settleTypeOption)){
                        $text .= "\n第【{$row_list}】行：默认结算方式不在可选范围内";
                    } else {
                        //查看范围
                        $field['see'] = implode(',',array_filter(array_unique(array_merge(explode(',', $field['collaborator']), [$field['manager']]))));
                        if (!empty($field['address'])){
                            //解析地址信息 得到经纬度和省市区
                            $locationRes= componentClass::addrToCoordinate($field['address']);
                            if ($locationRes['err_code'] == 0) {
                                $field['lat'] = $locationRes['data']['location']['lat'];
                                $field['lng'] = $locationRes['data']['location']['lng'];
                                $region = componentClass::coordinateToAddr($field['lat'], $field['lng']);
                                if ($region['err_code'] == 0) {
                                    $field['region'] = $region['data']['address_component']['province'] . '-' . $region['data']['address_component']['city'] . '-' . $region['data']['address_component']['district'];
                                }
                            }
                        }
                        $info = query(self::table,"orderNo = '$field[orderNo]' and coid = '".self::$coid."'");
                        if (empty($info['khid'])){
                            $field = array_merge($field,[
                                'khid' => $id,
                                'orderNo'=>$cell[0],
                                'coid'=>self::$coid,
                                'isDeal'=>1,
                                'data_source'=>1,
                                'stid'=>self::$stid,
                                "updateTime" => date("Y-m-d H:i:s"),//更新时间
                                'time' => $this->time,
                            ]);
                            $userNo = codeTemplateClass::generateCode(self::page,[
                                'prefix' => 'C',
                                'table' => self::table,
                                'field' => 'orderNo',
                                'where' => '',
                            ],$field);
                            $field['orderNo'] = $field['orderNo']?:$userNo;
                            $warn = insert(["table" => self::table, "field" => $field]);
                        }else{
                            $warn = update(["table" => self::table, "field" => $field,'where'=>"khid = '$info[khid]'"]);
                        }

                        if (in_array($warn, ["新增成功", "更新成功"])) {
                            if (!empty($field['contactName']) && !empty($field['contactTel'])){
                                $contact  =query('kehu_staff',"khid = '$id' and tel = '$field[contactTel]'");
                                if (empty($contact['id'])){
                                    static::insert(array(
                                        'table'=>'kehu_staff',
                                        'field'=>[
                                            'id'=>suiji(),
                                            'coid'=>self::$coid,
                                            'khid'=>$id,
                                            'stid'=>self::$stid,
                                            "name" => $field['contactName'],//姓名
                                            "tel" => $field['contactTel'],//手机
                                            "qq" => $field['contactQQ'],//QQ号码
                                            "WeChat" => $field['contactWx'],//微信号
                                            "text" => '常用联系人',//备注
                                        ]
                                    ));
                                }else{
                                    static::update(array(
                                        'table'=>'kehu_staff',
                                        'field'=>[
                                            "name" => $field['contactName'],//姓名
                                            "tel" => $field['contactTel'],//手机
                                            "qq" => $field['contactQQ'],//QQ号码
                                            "WeChat" => $field['contactWx'],//微信号
                                            "text" => '常用联系人',//备注
                                        ],
                                        'where'=>"id = '$contact[id]'"
                                    ));
                                }
                            }
                            $x++;
                            $text .= "第【{$row_list}】行：导入成功<br>";
                        } else {
                            $text .= "第【{$row_list}】行：导入失败：编辑失败<br>";
                        }
                    }
                }
            }
            $total = count($data)-1;
            $json['data'] = [
                'text'=>$text,
                'title'=>"您导入了{$total}条数据，成功{$x}条，失败".($total-$x)."条",
            ];
            $text = $this->control['name'] . '导入了文件：' . $_FILES['file']['name'] . '：' . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
        }
        return json_encode($json,320);
    }

    /**
     * 客户模糊查询
     * @return false|string
     */
    public function getClient(){
        $val = $this->post('keyword');//关键词
        $json['data'] = [];
        $where = "";
        if ($val){
            $where.=" and (companyName like '%$val%' or orderNo like '%$val%')";
        }
        $all = find(array('table' => 'kehu', 'where' => " coid = '" . self::$coid . "' $where  order by orderNo asc limit 50"));
        foreach ($all['array'] as $array) {
            $json['data'][] = array('title' => $array['orderNo'].'-'.$array['companyName'], 'id' => $array['khid']);
        }
        $json['warn'] = 2;
        return json_encode($json, 320);
    }
    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => self::table,
                    "where" => "khid in ('".implode("','", $checkedId)."') order by time desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '客户编号'=>$array['orderNo'],
                            '客户名称'=>$array['companyName'],
                            '性质'=>$array['nature'],
                            '常用联系人姓名'=>$array['contactName'],
                            '常用联系人手机'=>$array['contactTel'],
                            '常用联系人微信'=>$array['contactWx'],
                            '常用联系人QQ'=>$array['contactQQ'],
                            '客户级别'=>$array['level'],
                            '客户类别'=>$array['classify'],
                            '来源'=>$array['workFlow'],
                            '负责人'=> self::findStaff($array['manager']),
                            '协作人'=> clueClass::showMember($array['collaborator'], 2),
                            '发票类型'=>$array['invoiceType'],
                            '默认税率%'=>($array['taxRate']*100),
                            '开户行'=>$array['companyBank'],
                            '银行账号'=>$array['companyBankNum'],
                            '注册地址、电话'=>$array['companyAddress'],
                            '纳税人识别号'=>$array['companyNum'],
                            '默认付款方式'=>$array['settleType'],
                            '信用额度'=>$array['credits'],
                            '默认结算方式'=>$array['payType'],
                            '对账日'=>$array['checkDay'],
                            '备注'=>$array['text'],
                            '创建人'=> self::findStaff($array['stid']),
                            '更新时间'=>$array['updateTime'],
                            '创建时间'=>$array['time'],
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = $this->control['name'] . "导出了客户表";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "客户表.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));

    }

    /**
     * 导入模板字段初始化
     * @return array[]
     */
    public function importFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'客户编号',
                    'aliasName'=>'客户编号',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'客户名称',
                    'aliasName'=>'客户名称',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'性质',
                    'aliasName'=>'性质',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'常用联系人姓名',
                    'aliasName'=>'常用联系人姓名',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'常用联系人手机',
                    'aliasName'=>'常用联系人手机',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'常用联系人微信',
                    'aliasName'=>'常用联系人微信',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'常用联系人QQ',
                    'aliasName'=>'常用联系人QQ',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'收货地址',
                    'aliasName'=>'收货地址',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'客户级别',
                    'aliasName'=>'客户级别',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'客户类别',
                    'aliasName'=>'客户类别',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'来源',
                    'aliasName'=>'来源',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'负责人',
                    'aliasName'=>'负责人',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'负责人编号',
                    'aliasName'=>'负责人编号',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'协作人',
                    'aliasName'=>'协作人',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'协作人编号',
                    'aliasName'=>'协作人编号(多个用英文逗号隔开)',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'发票类型',
                    'aliasName'=>'发票类型',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'默认税率',
                    'aliasName'=>'默认税率%',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'开户行',
                    'aliasName'=>'开户行',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'银行账号',
                    'aliasName'=>'银行账号',

                    'isMust'=>false,
                ],

                [
                    'columnName'=>'注册地址、电话',
                    'aliasName'=>'注册地址、电话',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'纳税人识别号',
                    'aliasName'=>'纳税人识别号',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'默认付款方式',
                    'aliasName'=>'默认付款方式',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'信用额度',
                    'aliasName'=>'信用额度',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'默认结算方式',
                    'aliasName'=>'默认结算方式',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'对账日',
                    'aliasName'=>'对账日',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',

                    'isMust'=>false,
                ],
            ]
        };
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'客户编号',
                    'aliasName'=>'客户编号',
                ],
                [
                    'columnName'=>'客户名称',
                    'aliasName'=>'客户名称',
                ],
                [
                    'columnName'=>'性质',
                    'aliasName'=>'性质',
                ],
                [
                    'columnName'=>'常用联系人姓名',
                    'aliasName'=>'常用联系人姓名',
                ],
                [
                    'columnName'=>'常用联系人手机',
                    'aliasName'=>'常用联系人手机',
                ],
                [
                    'columnName'=>'常用联系人微信',
                    'aliasName'=>'常用联系人微信',
                ],
                [
                    'columnName'=>'常用联系人QQ',
                    'aliasName'=>'常用联系人QQ',
                ],
                [
                    'columnName'=>'客户级别',
                    'aliasName'=>'客户级别',
                ],
                [
                    'columnName'=>'客户类别',
                    'aliasName'=>'客户类别',
                ],
                [
                    'columnName'=>'来源',
                    'aliasName'=>'来源',
                ],
                [
                    'columnName'=>'负责人',
                    'aliasName'=>'负责人',
                ],
                [
                    'columnName'=>'协作人',
                    'aliasName'=>'协作人',
                ],
                [
                    'columnName'=>'发票类型',
                    'aliasName'=>'发票类型',
                ],
                [
                    'columnName'=>'默认税率',
                    'aliasName'=>'默认税率%',
                ],
                [
                    'columnName'=>'开户行',
                    'aliasName'=>'开户行',
                ],
                [
                    'columnName'=>'银行账号',
                    'aliasName'=>'银行账号',
                ],
                [
                    'columnName'=>'注册地址、电话',
                    'aliasName'=>'注册地址、电话',
                ],
                [
                    'columnName'=>'纳税人识别号',
                    'aliasName'=>'纳税人识别号',
                ],
                [
                    'columnName'=>'默认付款方式',
                    'aliasName'=>'默认付款方式',
                ],
                [
                    'columnName'=>'信用额度',
                    'aliasName'=>'信用额度(元)',
                ],
                [
                    'columnName'=>'默认结算方式',
                    'aliasName'=>'默认结算方式',
                ],
                [
                    'columnName'=>'对账日',
                    'aliasName'=>'对账日',
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',
                ],
                [
                    'columnName'=>'创建人',
                    'aliasName'=>'创建人',
                ],
                [
                    'columnName'=>'更新时间',
                    'aliasName'=>'更新时间',
                ],
                [
                    'columnName'=>'创建时间',
                    'aliasName'=>'创建时间',
                ],
            ]
        };
    }
}
